import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { fetchEventSource } from '@microsoft/fetch-event-source';
import { deleteV1DeleteConversation, DIFY_BASE_URL, getV1ConversationMessages } from "../service/yapi";
import { useUserStore } from "./user"; // 添加这行导入
let messageBuffer = '';
let updateTimeout: any = null;
const BATCH_UPDATE_INTERVAL = 50; // 50ms批量更新一次

export interface ChatMessage {
  id: string;
  sender: "user" | "assistant";
  text: string;
  timestamp: Date;
  isStreaming?: boolean;
  messageId?: string; // 服务器返回的消息ID
  query?: string; // 用户的原始查询
  answer?: string; // 助手的回答
  created_at?: number; // 消息创建时间
  parent_message_id?: string | null; // 父消息ID
  status?: string; // 消息状态
}

// 更新会话信息接口以匹配API返回
export interface Conversation {
  id: string;
  name?: string;
  inputs?: Record<string, any>;
  status?: string;
  introduction?: string;
  created_at?: number;
  updated_at?: number;
  messages: ChatMessage[]; // 会话的消息列表
  // 分页相关字段
  has_more?: boolean; // 是否有更多消息
  first_message_id?: string; // 当前第一条消息的ID，用于上滑加载更多
}

interface ConversationInfo {
  conversation_id: string;
  message_id: string;
}

interface MessageResponse {
  limit: number;
  has_more: boolean;
  data: Array<{
    id: string;
    conversation_id: string;
    parent_message_id: string | null;
    inputs: Record<string, any>;
    query: string;
    answer: string;
    message_files: any[];
    feedback: any;
    retriever_resources: any[];
    created_at: number;
    agent_thoughts: any[];
    status: string;
    error: any;
  }>;
}

export const useChatStore = defineStore("chat", () => {
  // 当前活跃的会话ID
  const activeConversationId = ref<string>("");

  // 修改会话列表的数据结构，使其符合API返回格式
  const conversations = ref<{ [key: string]: Conversation }>({});

  // 是否正在加载历史消息
  const isLoadingHistory = ref(false);

  // 控制器，用于中止请求
  let controller: AbortController | null = null;

  // 当前是否正在生成回答
  const isGenerating = ref(false);

  // 获取当前会话的消息
  const currentMessages = computed(() => {
    if (!activeConversationId.value || !conversations.value[activeConversationId.value]) {
      return [];
    }
    return conversations.value[activeConversationId.value].messages || [];
  });

  // 创建新会话 - 修改为不预设 ID
  const createNewConversation = () => {
    // 检查是否已有临时会话，如果有则不创建
    const hasTemp = Object.keys(conversations.value).some(id => id.startsWith('temp_'))
    if (hasTemp) {
      console.log("已存在临时会话，不再创建")
      return Object.keys(conversations.value).find(id => id.startsWith('temp_'))
    }
    // 使用临时ID，等待服务器返回实际ID
    const tempId = `temp_${Date.now()}`;

    // 创建新的会话对象
    const newConversation = {
      id: tempId,
      name: "新会话",
      messages: [],
      has_more: false,
      created_at: Math.floor(Date.now() / 1000), // 添加创建时间戳
      updated_at: Math.floor(Date.now() / 1000)  // 添加更新时间戳
    };

    // 创建一个新的对象，先放入新会话，再合并现有会话
    const updatedConversations = {
      [tempId]: newConversation,
      ...conversations.value
    };

    // 更新会话列表
    conversations.value = updatedConversations;
    activeConversationId.value = tempId;
    return tempId;
  };

  // 选择会话并加载消息
  const selectConversation = async (id: string, loadMessages = true, appId: any, appuserId: any) => {
    if (conversations.value[id]) {
      activeConversationId.value = id;

      // 如果是真实会话ID(非临时)且需要加载消息，并且当前没有消息，则加载消息
      if (loadMessages && !id.startsWith('temp_') && (!conversations.value[id].messages || conversations.value[id].messages.length === 0)) {
        await loadConversationMessages(id, '', appId, appuserId);
      }
    }
  };

  // 加载会话消息
  const loadConversationMessages = async (conversationId: string, firstId?: string, appId?: any, appuserId?: any) => {
    if (!conversationId || conversationId.startsWith('temp_')) return;

    try {
      isLoadingHistory.value = true;

      const params: any = {
        conversation_id: conversationId,
        limit: 20,
        appId,
        appuserId,
        platform: "momoai"
      };

      if (firstId) {
        params.first_id = firstId;
      }

      const response = await getV1ConversationMessages(params);

      if (response && response.data) {
        const messagesResponse = response as MessageResponse;

        // 更新会话的has_more状态
        if (conversations.value[conversationId]) {
          conversations.value[conversationId].has_more = messagesResponse.has_more;

          // 如果有消息，设置第一条消息的ID用于分页
          if (messagesResponse.data.length > 0) {
            conversations.value[conversationId].first_message_id = messagesResponse.data[0].id;
          }

          // 将接口返回的消息分解为用户消息和助手消息
          const formattedMessages: ChatMessage[] = [];

          // 处理每条API消息，拆分为用户和助手两条消息
          messagesResponse.data.forEach(apiMessage => {
            // 如果有用户查询，添加用户消息
            if (apiMessage.query) {
              formattedMessages.push({
                id: `user_${apiMessage.id}`,
                messageId: apiMessage.id,
                sender: "user",
                text: apiMessage.query,
                timestamp: new Date(apiMessage.created_at * 1000),
                query: apiMessage.query,
                created_at: apiMessage.created_at,
                parent_message_id: apiMessage.parent_message_id,
                status: apiMessage.status,
                isStreaming: false
              });
            }

            // 如果有助手回答，添加助手消息
            if (apiMessage.answer) {
              formattedMessages.push({
                id: `assistant_${apiMessage.id}`,
                messageId: apiMessage.id,
                sender: "assistant",
                text: apiMessage.answer,
                timestamp: new Date(apiMessage.created_at * 1000),
                answer: apiMessage.answer,
                created_at: apiMessage.created_at,
                parent_message_id: apiMessage.parent_message_id,
                status: apiMessage.status,
                isStreaming: false
              });
            }
          });

          // 按照时间排序
          formattedMessages.sort((a, b) => a.created_at! - b.created_at!);

          if (firstId) {
            // 如果是加载更多，则将新消息添加到开头
            conversations.value[conversationId].messages = [...formattedMessages, ...conversations.value[conversationId].messages];
          } else {
            // 如果是首次加载，直接设置消息
            conversations.value[conversationId].messages = formattedMessages;
          }
        }
      }
    } catch (error) {
      console.error('Failed to load conversation messages:', error);
    } finally {
      isLoadingHistory.value = false;
    }
  };

  const updateConversationInputs = (inputs: Record<string, any>) => {
    if (!activeConversationId.value || !conversations.value[activeConversationId.value]) return;

    // 更新inputs属性
    conversations.value[activeConversationId.value].inputs = {
      ...conversations.value[activeConversationId.value].inputs || {},
      ...inputs
    };

    console.log("Conversation inputs updated:", inputs);
  };
  // 映射API消息到本地消息格式
  const mapApiMessageToChatMessage = (apiMessage: any): ChatMessage[] => {
    // 创建时间戳
    const timestamp = new Date(apiMessage.created_at * 1000);
    const messages: ChatMessage[] = [];

    // 如果有用户查询，添加用户消息
    if (apiMessage.query) {
      messages.push({
        id: `user_${apiMessage.id}`,
        messageId: apiMessage.id,
        sender: "user",
        text: apiMessage.query,
        timestamp,
        query: apiMessage.query,
        created_at: apiMessage.created_at,
        parent_message_id: apiMessage.parent_message_id,
        status: apiMessage.status,
        isStreaming: false
      });
    }

    // 如果有助手回答，添加助手消息
    if (apiMessage.answer) {
      messages.push({
        id: `assistant_${apiMessage.id}`,
        messageId: apiMessage.id,
        sender: "assistant",
        text: apiMessage.answer,
        timestamp,
        answer: apiMessage.answer,
        created_at: apiMessage.created_at,
        parent_message_id: apiMessage.parent_message_id,
        status: apiMessage.status,
        isStreaming: false
      });
    }

    return messages;
  };

  // 添加用户消息
  const addUserMessage = (text: string) => {
    if (!activeConversationId.value) {
      createNewConversation();
    }

    const message: ChatMessage = {
      id: `msg_user_${Date.now()}`,
      sender: "user",
      text,
      query: text,
      timestamp: new Date()
    };

    if (!conversations.value[activeConversationId.value].messages) {
      conversations.value[activeConversationId.value].messages = [];
    }

    conversations.value[activeConversationId.value].messages.push(message);

    // 如果是第一条消息，更新会话名称
    if (conversations.value[activeConversationId.value].messages.length === 1) {
      conversations.value[activeConversationId.value].name = text.substring(0, 20) + (text.length > 20 ? '...' : '');
    }

    return message;
  };

  // 添加AI消息
  const addAssistantMessage = (initialText: string = "") => {
    const message: ChatMessage = {
      id: `msg_ai_${Date.now()}`,
      sender: "assistant",
      text: initialText,
      answer: initialText,
      timestamp: new Date(),
      isStreaming: true
    };

    if (!conversations.value[activeConversationId.value].messages) {
      conversations.value[activeConversationId.value].messages = [];
    }

    conversations.value[activeConversationId.value].messages.push(message);
    return message;
  };

  // 更新消息内容 - 修改为累加模式
  // 优化更新消息文本的方法
  const updateMessageText = (messageId: string, text: string, shouldAppend: boolean = false) => {
    if (!activeConversationId.value) return;

    const messages = conversations.value[activeConversationId.value].messages;
    const messageIndex = messages.findIndex(msg => msg.id === messageId);

    if (messageIndex !== -1) {
      // 使用函数更新以提高性能
      if (shouldAppend) {
        // 对于大量文本，直接使用新字符串而不是+=操作
        const currentText = messages[messageIndex].text || '';
        messages[messageIndex].text = currentText + text;

        if (messages[messageIndex].answer !== undefined) {
          const currentAnswer = messages[messageIndex].answer || '';
          messages[messageIndex].answer = currentAnswer + text;
        }
      } else {
        // 替换模式不变
        messages[messageIndex].text = text;
        if (messages[messageIndex].answer !== undefined) {
          messages[messageIndex].answer = text;
        }
      }

      // 如果消息长度超过一定限制，考虑截断或分段处理
      const MAX_MESSAGE_LENGTH = 100000; // 设置合理的最大长度
      if (messages[messageIndex].text.length > MAX_MESSAGE_LENGTH) {
        // 可以考虑截断或划分消息
        console.warn('Message exceeding size limit, consider pagination or virtualization');
      }
    }
  };

  // 加载更多历史消息
  const loadMoreMessages = async () => {
    if (!activeConversationId.value ||
      activeConversationId.value.startsWith('temp_') ||
      isLoadingHistory.value ||
      !conversations.value[activeConversationId.value].has_more) {
      return false;
    }

    const firstMessageId = conversations.value[activeConversationId.value].first_message_id;
    await loadConversationMessages(activeConversationId.value, firstMessageId);
    return true;
  };

  // 完成流式消息
  const finishStreamingMessage = (messageId: string) => {
    if (!activeConversationId.value) return;

    const messages = conversations.value[activeConversationId.value].messages;
    const messageIndex = messages.findIndex(msg => msg.id === messageId);

    if (messageIndex !== -1) {
      messages[messageIndex].isStreaming = false;
    }

    isGenerating.value = false;
  };

  // 设置服务器返回的会话ID
  const setServerConversationId = (tempId: string, serverId: string) => {
    if (conversations.value[tempId]) {
      // 保存原会话消息
      const conversation = conversations.value[tempId];

      // 创建新的会话对象并重建会话列表，确保新会话在最前面
      const updatedConversations: { [key: string]: Conversation } = {};

      // 首先添加新的服务器ID会话
      updatedConversations[serverId] = {
        ...conversation,
        id: serverId
      };

      // 然后添加其他会话
      Object.keys(conversations.value).forEach(id => {
        if (id !== tempId) {
          updatedConversations[id] = conversations.value[id];
        }
      });

      // 更新会话列表
      conversations.value = updatedConversations;

      // 如果当前活跃ID是临时ID，将其更新为服务器ID
      if (activeConversationId.value === tempId) {
        activeConversationId.value = serverId;
      }
    }
  };

  // 设置从服务器获取的会话列表
  const setConversations = async (serverConversations: any[], appId: Number, appuserId: Number) => {
    // 先转换数据格式
    const formattedConversations: { [key: string]: Conversation } = {};
    // 按照创建时间排序会话，最新的在前面
    const sortedConversations = [...serverConversations].sort((a, b) =>
      (b.updated_at || b.created_at) - (a.updated_at || a.created_at)
    );

    // 处理服务器返回的会话数据
    sortedConversations.forEach(conv => {
      formattedConversations[conv.id] = {
        id: conv.id,
        name: conv.name,
        inputs: conv.inputs,
        status: conv.status,
        introduction: conv.introduction,
        created_at: conv.created_at,
        updated_at: conv.updated_at,
        messages: [], // 初始为空数组，稍后单独加载消息
        has_more: false
      };
    });

    // 合并现有的本地会话（可能包含临时会话）
    const mergedConversations = { ...formattedConversations };

    // 保留所有临时会话
    Object.keys(conversations.value).forEach(id => {
      if (id.startsWith('temp_')) {
        mergedConversations[id] = conversations.value[id];
      }
    });

    // 更新会话列表
    conversations.value = mergedConversations;

    // 获取会话ID列表
    const convIds = Object.keys(formattedConversations);

    // 判断是否有服务器会话，且判断第一个会话是否在5小时以内
    if (convIds.length > 0) {
      const firstConv = formattedConversations[convIds[0]];
      const currentTimestamp = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
      // ts-ignore
      const createdAt = firstConv.created_at || 0;
      const timeDiffHours = (currentTimestamp - createdAt) / 3600; // 转换为小时

      console.log(`最新会话创建时间: ${new Date(createdAt * 1000).toLocaleString()}, 时间差: ${timeDiffHours.toFixed(2)}小时`);

      if (timeDiffHours < 5) {
        // 如果在5小时以内，选择第一个服务器会话
        console.log("选择最近的服务器会话");
        await selectConversation(convIds[0], true, appId, appuserId);
      } else {
        // 如果超过5小时，创建并选择新会话
        console.log("最近会话超过5小时，创建新会话");
        createNewConversation();
      }
    } else if (!activeConversationId.value) {
      // 如果没有服务器会话且没有活跃会话，创建一个新的临时会话
      console.log("没有服务器会话，创建新会话");
      createNewConversation();
    }
  };

  // 发送消息并获取回复
  const sendMessage = async (params: any = {}, apiHeaders: any = {}) => {
    const { text, inputs = {} } = params;

    if (!text.trim()) return;

    // 保存当前会话ID，可能是临时ID
    const currentId = activeConversationId.value;

    // 查找上一条助手消息的ID
    let parentMessageId = "";
    if (conversations.value[currentId]) {
      const messages = conversations.value[currentId].messages || [];
      // 筛选所有助手消息并找到最后一条
      const assistantMessages = messages.filter(msg => msg.sender === 'assistant');
      if (assistantMessages.length > 0) {
        const lastAssistantMessage = assistantMessages[assistantMessages.length - 1];
        // 如果存在服务端返回的消息ID，则使用它作为parent_message_id
        parentMessageId = lastAssistantMessage.messageId || "";
      }
    }

    // 添加用户消息
    addUserMessage(text);

    // 创建助手消息占位
    const assistantMessage = addAssistantMessage();
    isGenerating.value = true;

    // 准备请求体
    const requestBody = {
      message: text,
      // 如果当前ID是以temp_开头，则不发送conversation_id
      conversation_id: currentId.startsWith('temp_') ? undefined : currentId,
      platform: "momoai",
      query: text,
      appId: apiHeaders.appId,
      appuserId: apiHeaders.appuserId,
      files: [],
      inputs: inputs, // 使用传入的inputs参数
      parent_message_id: parentMessageId,
      response_mode: "streaming",
    };

    try {
      controller = new AbortController();

      await fetchEventSource(DIFY_BASE_URL + '/v1', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...apiHeaders
        },
        body: JSON.stringify(requestBody),
        signal: controller.signal,
        onopen: async (response) => {
          if (response.status === 403) {
            // 处理403权限不足的情况
            updateMessageText(assistantMessage.id, "您没有权限访问此功能，请联系管理员或升级您的账户。");
            finishStreamingMessage(assistantMessage.id);
            controller?.abort();
            throw new Error("Permission denied");
          } else if (response.status !== 200) {
            // 处理其他错误
            updateMessageText(assistantMessage.id, `请求错误 (${response.status}): 请稍后重试或联系客服。`);
            finishStreamingMessage(assistantMessage.id);
            controller?.abort();
            throw new Error(`Server responded with ${response.status}`);
          }
        },
        onmessage: (event) => {
          try {
            // 尝试解析 JSON 数据
            const data = JSON.parse(event.data);

            // 处理会话信息
            if (data.conversation_id || data.message_id) {
              updateConversationInfo({
                conversation_id: data.conversation_id || "",
                message_id: data.message_id || ""
              });
            }

            // 使用批量缓冲区收集答案片段，增强 emoji 支持
            if (data.answer !== undefined) {
              // 确保 data.answer 是字符串类型
              const answer = typeof data.answer === 'string' ? data.answer : String(data.answer);

              // 处理可能的 Unicode 转义序列 (如 \u1F600 格式的 emoji)
              const decodedAnswer = answer.replace(/\\u([0-9a-fA-F]{4})/g, (match, hex) => {
                return String.fromCodePoint(parseInt(hex, 16));
              });

              messageBuffer += decodedAnswer;

              // 清除之前的定时器
              if (updateTimeout) clearTimeout(updateTimeout);

              // 设置新的定时器进行批量更新
              updateTimeout = setTimeout(() => {
                if (messageBuffer) {
                  try {
                    const isFirstUpdate = assistantMessage.text === "";
                    // 批量更新UI
                    updateMessageText(assistantMessage.id, messageBuffer, !isFirstUpdate);
                    messageBuffer = ''; // 清空缓冲区
                  } catch (updateError) {
                    console.error('Error updating message text:', updateError);
                    // 尝试进行分段更新以提高稳定性
                    try {
                      const chunkSize = 500; // 设置合理的分块大小
                      const chunks = [];

                      for (let i = 0; i < messageBuffer.length; i += chunkSize) {
                        chunks.push(messageBuffer.substring(i, i + chunkSize));
                      }

                      // 逐个处理每个分块
                      for (const chunk of chunks) {
                        updateMessageText(assistantMessage.id, chunk, true);
                      }

                      messageBuffer = '';
                    } catch (fallbackError) {
                      console.error('Fallback update failed:', fallbackError);
                    }
                  }
                }
              }, BATCH_UPDATE_INTERVAL);
            }
          } catch (error) {
            console.error('Error parsing message:', error);

            // 尝试处理非 JSON 数据或特殊字符串
            if (event.data && typeof event.data === 'string') {
              try {
                // 尝试直接处理原始文本
                const rawText = event.data.trim();

                if (rawText) {
                  // 尝试解码转义序列
                  const decodedText = rawText.replace(/\\u([0-9a-fA-F]{4})/g, (match, hex) => {
                    return String.fromCodePoint(parseInt(hex, 16));
                  });

                  messageBuffer += decodedText;

                  // 清除之前的定时器
                  if (updateTimeout) clearTimeout(updateTimeout);

                  // 设置新的定时器
                  updateTimeout = setTimeout(() => {
                    if (messageBuffer) {
                      const isFirstUpdate = assistantMessage.text === "";
                      updateMessageText(assistantMessage.id, messageBuffer, !isFirstUpdate);
                      messageBuffer = '';
                    }
                  }, BATCH_UPDATE_INTERVAL);
                }
              } catch (innerError) {
                console.error('Failed to process raw data:', innerError);
              }
            }

            // 不抛出错误，确保流处理继续
          }
        },
        onerror: (error) => {
          console.error('Stream error:', error);
          if (!error.toString().includes("Permission denied")) {
            updateMessageText(assistantMessage.id, "连接出错，请检查您的网络或稍后重试。");
            finishStreamingMessage(assistantMessage.id);
          }
          controller?.abort();
        }
      });

    } catch (error) {
      console.error('Error sending message:', error);
      // 如果不是权限错误，显示通用错误信息
      if (!error.toString().includes("Permission denied")) {
        updateMessageText(assistantMessage.id, "很抱歉，发生了错误，请稍后再试。");
      }
      controller?.abort();
    } finally {
      // 只在finally块中调用一次 finishStreamingMessage
      finishStreamingMessage(assistantMessage.id);
      controller?.abort();
    }
  };

  // 停止生成
  const stopGenerating = () => {
    if (controller) {
      controller.abort();
      controller = null;
      isGenerating.value = false;
    }
  };

  // 更新会话信息
  const updateConversationInfo = (info: ConversationInfo) => {
    // 保存会话ID和消息ID到当前活跃会话
    if (!activeConversationId.value) return;

    // 如果当前会话ID是临时ID，更新为服务器返回的ID
    if (activeConversationId.value.startsWith('temp_') && info.conversation_id) {
      setServerConversationId(activeConversationId.value, info.conversation_id);
    }

    // 更新最后一条助手消息的messageId
    if (info.message_id && conversations.value[activeConversationId.value]) {
      const messages = conversations.value[activeConversationId.value].messages;
      const assistantMessages = messages.filter(msg => msg.sender === 'assistant');
      if (assistantMessages.length > 0) {
        const lastAssistantMessage = assistantMessages[assistantMessages.length - 1];
        lastAssistantMessage.messageId = info.message_id;
      }
    }

  };

  // 清空当前会话
  const clearCurrentConversation = () => {
    if (activeConversationId.value) {
      conversations.value[activeConversationId.value].messages = [];
    }
  };

  // 删除会话
  const deleteConversation = async (id: string, appId: Number, appuserId: Number) => {

    // 只有当是真实会话(不是临时会话)时才调用API删除
    if (conversations.value[id] && !id.startsWith('temp_')) {
      try {
        // 调用API删除服务器上的会话
        await deleteV1DeleteConversation({
          conversation_id: id,
          appId,
          appuserId,
          platform: "momoai"
        });
        console.log(`会话 ${id} 已从服务器删除`);
      } catch (error) {
        console.error(`删除服务器会话失败:`, error);
        // 即使服务器删除失败，我们仍然继续删除本地会话
      }
    }
    if (conversations.value[id]) {
      delete conversations.value[id];

      if (activeConversationId.value === id) {
        // 如果删除的是当前活跃会话，选择另一个或创建新的
        const conversationIds = Object.keys(conversations.value);
        if (conversationIds.length > 0) {
          selectConversation(conversationIds[0], true, appId, appuserId);
        } else {
          createNewConversation();
        }
      }
    }
  };

  return {
    activeConversationId,
    conversations,
    currentMessages,
    isGenerating,
    isLoadingHistory,
    createNewConversation,
    selectConversation,
    sendMessage,
    addUserMessage,
    addAssistantMessage,
    updateMessageText,
    stopGenerating,
    clearCurrentConversation,
    deleteConversation,
    setServerConversationId,
    setConversations,
    loadMoreMessages,
    loadConversationMessages,
    updateConversationInputs
  };
});